package main

import (
	"encoding/json"
	"sync"
)

type Room struct {
	id string
	clients map[*Client]bool

	broadcastMsg chan []byte

	leaving chan *Client
	entering chan *Client
}

type Rooms struct {
	rooms map[string]*Room

	mux sync.Mutex
}

func newRooms() *Rooms {
	return &Rooms{
		rooms: make(map[string]*Room),
	}
}

func (r *Room) broadcast() {
	for {
		select {
		case cli := <-r.entering:
			msg := WriteData{
				Data{MsgType:joinMsg, Msg: cli.conn.RemoteAddr().String()},
			}
			byteMsg, _ := json.Marshal(msg)
			for client := range r.clients {
				client.bufChan <- byteMsg
			}
			r.clients[cli] = true
		case cli := <-r.leaving:
			delete(r.clients, cli)
			close(cli.bufChan)
		case msg := <-r.broadcastMsg:
			for cli := range r.clients {
				cli.bufChan <- msg
			}
		}
	}
}